let _u_token = u_token
let max_length = 10
$('#upload').on('click', '', function () {
    if (!checkLogin()) return false
})
$('#continuePicker').on('click', '', function () {
    let ul_len = $('.table-body ul').length
    if (ul_len > max_length) return false
    $('.interface-upload').find('input:last').click();
})
let _accept = $('#upload').data('accept')
let _extensions = $('#upload').data('extensions')
let _multiple = $('#upload').data('multiple')
_multiple = _multiple ? true : false
var uploader = WebUploader.create({
    swf: '/static/webuploader/Uploader.swf',
    server: '/ajax/upload/',
    pick: {id: '#upload', multiple: _multiple},
    resize: false,
    dnd: '#upload',
    disableGlobalDnd: false,
    accept: {
        title: '文件上传',
        extensions: _extensions,
        mimeTypes: _accept,
    },
    fileNumLimit: _multiple ? max_length : 1,
    chunked: true,
    threads: 1,
    method: 'POST',
    fileSizeLimit: 1024 * 1024 * max_size_limit,
    fileSingleSizeLimit: 1024 * 1024 * max_size_limit,
    fileVal: 'upload',
    duplicate: true
});
uploader.on('beforeFileQueued', function () {
    console.log('beforeFileQueued')
    if (!checkLogin()) return false
    // if (!checkVip()) return false
})
uploader.on('fileQueued', function (file) {
    $('.converter-interface').addClass('element-invisible')
    $('.converter-function').removeClass('element-invisible')
    let html = '<ul class="table-tbody-tr">\n' +
        '<li class="table-tbody-td" style="width:407px;color:#222;" title="' + file.name + '">' + file.name + '</li>\n' +
        '<li class="table-tbody-td" style="width:141px;color:#666;">' + changeByte(file.size) + '</li>\n' +
        '<li class="table-tbody-td progress ' + file.id + '" style="width:185px;color:#666;">\n' +
        '    <span>准备上传</span>\n' +
        '</li>\n' +
        '<li class="table-tbody-td action" style="width:110px;color:#CCCDD1;">\n' +
        '    <span class="action-btn iconfont icon-shanchu btn-remove" data-file_id="' + file.id + '" title="删除"></span>\n' +
        '</li>\n' +
        '</ul>';
    $('.table-body').append(html);
    // $('#continuePicker').attr("disabled", "disabled");
    // $('#continuePicker').addClass("disabled");
    $('#upload2').find('label:first').css({"cursor": "not-allowed"})
});
uploader.on("error", function (type) {
    if (type == "Q_TYPE_DENIED") {
        layerFailed("请上传正确的格式文件");
    } else if (type == "Q_EXCEED_SIZE_LIMIT") {
        if (is_vip < 1) {
            layer.confirm('非VIP会员只能上传 ' + max_size_limit + 'M 以内文件，要转换更大的文件可升级为VIP会员。', {
                btn: ['点击前往升级成VIP'], title: "升级VIP", closeBtn: 2
            }, function () {
                $('.op-vip').trigger('click')
            })
            return
        }
        layerFailed("文件大小不能超过" + max_size_limit + "M");
    } else if (type == "Q_EXCEED_NUM_LIMIT") {
        layerFailed("当前类型不支持上传更多");
    } else {
        layerFailed("上传出错！请检查后重新上传！错误代码" + type);
    }
});
uploader.on("uploadStart", function (start) {
    console.log("uploadStart")
});
uploader.on('uploadProgress', function (file, percentage) {
});
uploader.on('uploadSuccess', function (file, response) {
    let code = response.code || 400
    let data = response.data
    let _date = data.date
    if (code == '200') {
        layerSuccess(response.msg, {
            'shade': [0.3, '#000'], 'time': 800
        })
        setTimeout(function () {
            // location.reload()
        }, 1200)
    } else {
        layerFailed(response.msg, {
            'shade': [0.3, '#000']
        })
    }
    console.log(file.id + "传输成功");
});
uploader.on('uploadError', function (file) {
    console.log(file.id + 'upload error')
});
uploader.on('uploadComplete', function (file) {
    console.log('uploadComplete');
});
$('.table-body').on('click', '.btn-remove', function () {
    uploader.removeFile($(this).data('file_id'), true); // 从队列中删除
    $(this).parents('.table-tbody-tr').remove()
    let ul_len = $('.table-body ul').length
    if (ul_len < 1) {
        $('.continue-holder').remove()
        $('.table-btn-add').find('div:last').hide()
        $('.table-btn-add.webuploader-container').removeClass('disabled')
        uploader.reset();
    }
});
$('.table-btn-convert').on('click', '', function () {
    if (!checkLogin()) return false
    // if (!checkVip()) return false
    layer.msg('转换中...', {
        icon: 1,
        shade: [0.3, '#000'], time: 20000,
        shadeClose: false
    })
    let files = uploader.getFiles()
    let _files = []
    let _files_source = []
    files.forEach(function (eve) {
        _files.push(eve.source)
        _files_source.push(eve.source.source)
    });
    let _form_arr = $('#' + _type_title + '_form').serializeArray()
    let _extend = {}
    $.each(_form_arr, function () {
        _extend[this.name] = this.value;
    });
    _extend = JSON.stringify(_extend)
    fetch('/ajax/upload/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            'file': _files, '_u_token': _u_token
        })
    }).then(e => e.json()).then((res) => {
        let code = res.code || 400
        if (code == '412') {
            $('.jsOpenLoginLayer').trigger('click')
            return
        }
        if (code == '400') {
            layerFailed(res.msg)
            return
        }
        if (code == '413') {
            layer.confirm(res.msg, {
                btn: ['点击前往升级成VIP'], title: "升级VIP", closeBtn: 2
            }, function () {
                $('.op-vip').trigger('click')
            })
            return
        }
        let data = res.data
        const client = new OSS({
            region: 'oss-cn-shanghai',
            accessKeyId: data.AccessKeyId,
            accessKeySecret: data.AccessKeySecret,
            // 从STS服务获取的安全令牌（SecurityToken）。
            stsToken: data.SecurityToken,
            refreshSTSTokenInterval: 300000,
            bucket: 'docdata'
        });
        let _object = data.object
        let _file_name = data.file_name
        let _ext = []
        let length = _files_source.length
        var _final_object = []
        for (var ix = 0; ix < length; ix++) {
            _ext.push((_files_source[ix].name).split('.').pop().toLowerCase())
        }
        for (let i = 0; i < length; i++) {
            var p = new Promise(
                function (resolve, reject) {
                    try {
                        client.put(_object + '_' + i + '.' + _ext[i], _files_source[i]).then(function (r1) {
                            _final_object.push(r1.name)
                            resolve(_final_object)
                        })
                    } catch (err) {
                        console.error('error: %j', err);
                    }
                }
            )
        }
        setTimeout(function () {
            p.then(function (ret) {
                console.log(length)
                console.log(ret.length)
                if (ret.length == length) {
                    asyncUpload(_object, length, _file_name, _ext, _extend).then(r => {
                    })
                } else {
                    layerFailed('上传文件发生异常，请重试')
                }
            })
        }, 700)
    })
})
// 所有文件上传成功
uploader.on('uploadFinished', function () {
    console.log('uploadFinished')
    //清空队列
    $('.table-body').html('')
    $('.continue-holder').remove()
    uploader.reset();
})

async function asyncUpload(object, length, file_name, ext, extend) {
    layerSuccess('上传中...', 20000)
    await fetch('/ajax/converter/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            'object': object, 'file_name': file_name, 'type_title': _type_title,
            'ext': ext, 'length': length, 'extend': extend
        })
    }).then(e => e.json()).then((ret) => {
        let _code = ret.code || 400
        if (_code == 200) {
            layerSuccess('转换任务已提交...', {
                'shade': [0.3, '#000'], 'time': 20000
            })
            $('.table-body').html('')
            $('.continue-holder').remove()
            uploader.reset();
            setTimeout(function () {
                location.href = '/user/'
            }, 800)
        } else {
            layerFailed(ret.msg)
        }
    })
}
